import { useEffect, useState } from "react";
import {
    Skeleton, Space, Table, Typography, Tag, Form, Input,
    Select, Button, Row, Col, Card, Modal, Tabs, Badge,
    Dropdown, Menu, message
} from "antd";
import "./customer.css";
import {
    SearchOutlined, PlusOutlined, MoreOutlined,
    CheckCircleOutlined, UserOutlined, SyncOutlined
} from '@ant-design/icons';
import {CustomerDetails} from "../../component/customer/CustomerDetails"
import { AllocationEmploye } from "./allocationEmployee";
// 导入客户详情组件

const { Option } = Select;
const { Title, Text, Paragraph } = Typography;

// 客户类型映射（接口数字 → 前端显示）
const CUSTOMER_TYPE_MAP = {
    0: { text: "潜在客户", color: "purple" },
    1: { text: "正式客户", color: "geekblue" },
    2: { text: "公海客户", color: "orange" }
};

// 跟进状态映射（接口数字 → 前端显示）
const FOLLOW_STATUS_MAP = {
    0: { text: "待跟进", color: "warning" },
    1: { text: "跟进中", color: "processing" },
    2: { text: "已成交", color: "success" },
    3: { text: "已放弃", color: "error" }
};

// 模拟后台接口返回数据
const customerData = [
    {
        key: "1",
        customerNo: "CUS2023001",
        name: "张三",
        phone: "13800138000",
        type: 0,
        status: 1,
        followUpPerson: "",
        lastFollowUp: "-",
        nextFollowUp: "-",
        source: "线上咨询",
        gender: "男",
        totalConsumption: 0,
        remainingPoints: 0,
        consumedServices: [],
        lastVisit: "-",
        registered: false,
        avatar: "http://116.62.217.197:9921/yaoyaoche/Goods/Cover/04060c0c0271000e1651147cbfc56e47.jpg"
    },
    {
        key: "2",
        customerNo: "CUS2023002",
        name: "李四",
        phone: "13900139000",
        type: 0,
        status: 1,
        followUpPerson: "王销售",
        lastFollowUp: "2023-06-20",
        nextFollowUp: "2023-06-25",
        source: "朋友推荐",
        gender: "女",
        totalConsumption: 0,
        remainingPoints: 0,
        consumedServices: [],
        lastVisit: "-",
        registered: false
    },
    {
        key: "3",
        customerNo: "CUS2023003",
        name: "王五",
        phone: "13700137000",
        type: 1,
        status: 2,
        followUpPerson: "张销售",
        lastFollowUp: "2023-06-15",
        nextFollowUp: "2023-07-01",
        source: "线下门店",
        gender: "男",
        totalConsumption: 3680.00,
        remainingPoints: 2150,
        consumedServices: ["全身SPA", "中医理疗"],
        lastVisit: "2023-06-16",
        registered: true
    },
    {
        key: "4",
        customerNo: "CUS2023004",
        name: "赵六",
        phone: "13600136000",
        type: 2,
        status: 3,
        followUpPerson: "",
        lastFollowUp: "2023-05-10",
        nextFollowUp: "-",
        source: "展会",
        gender: "女",
        totalConsumption: 0,
        remainingPoints: 0,
        consumedServices: [],
        lastVisit: "-",
        registered: false
    },
    {
        key: "5",
        customerNo: "CUS2023005",
        name: "孙七",
        phone: "13500135000",
        type: 1,
        status: 2,
        followUpPerson: "李销售",
        lastFollowUp: "2023-06-18",
        nextFollowUp: "2023-06-30",
        source: "线上推广",
        gender: "男",
        totalConsumption: 1280.00,
        remainingPoints: 850,
        consumedServices: ["面部护理", "精油按摩"],
        lastVisit: "2023-06-15",
        registered: true
    }
];

// 销售列表
export const salesList = [
    { key: "1", name: "李销售" },
    { key: "2", name: "王销售" },
    { key: "3", name: "张销售" },
    { key: "4", name: "刘销售" }
];

export const CustomerManagement = () => {
    const [loading, setLoading] = useState(true);
    const [detailModalVisible, setDetailModalVisible] = useState(false);
    const [assignModalVisible, setAssignModalVisible] = useState(false);
    const [selectedCustomer, setSelectedCustomer] = useState(null);
    const [currentTab, setCurrentTab] = useState("all");
    const [filteredData, setFilteredData] = useState([]);
    const [form] = Form.useForm();
    const [selectedSales, setSelectedSales] = useState("");

    // 初始化加载
    useEffect(() => {
        const timer = setTimeout(() => {
            setLoading(false);
            setFilteredData(customerData);
        }, 1500);
        return () => clearTimeout(timer);
    }, []);

    // 标签页筛选
    useEffect(() => {
        switch (currentTab) {
            case "all":
                setFilteredData(customerData);
                break;
            case "potential":
                setFilteredData(customerData.filter(item => item.type === 0));
                break;
            case "official":
                setFilteredData(customerData.filter(item => item.type === 1));
                break;
            case "public":
                setFilteredData(customerData.filter(item => item.type === 2));
                break;
            default:
                setFilteredData(customerData);
        }
    }, [currentTab]);

    // 搜索筛选
    const handleSearch = () => {
        form.validateFields()
            .then(values => {
                const { searchKey, customerType, followUpStatus } = values;
                let result = [...customerData];

                if (searchKey) {
                    const keyword = searchKey.toLowerCase();
                    result = result.filter(item =>
                        item.name.toLowerCase().includes(keyword) ||
                        item.phone.includes(keyword) ||
                        item.customerNo.toLowerCase().includes(keyword)
                    );
                }

                if (customerType !== undefined && customerType !== null) {
                    result = result.filter(item => item.type === customerType);
                }

                if (followUpStatus !== undefined && followUpStatus !== null) {
                    result = result.filter(item => item.status === followUpStatus);
                }

                setFilteredData(result);
            })
            .catch(info => {
                console.log("筛选失败：", info);
            });
    };

 


    // 重置筛选
    const handleReset = () => {
        form.resetFields();
        setFilteredData(customerData);
    };

    // 查看详情
    const handleViewDetail = (key) => {
        const customer = customerData.find(item => item.key === key);
        if (customer) {
            setSelectedCustomer(customer);
            setDetailModalVisible(true);
        }
    };

    // 关闭详情模态框
    const handleCloseDetailModal = () => {
        setDetailModalVisible(false);
        setSelectedCustomer(null);
    };

    // 打开分配模态框
    const handleOpenAssignModal = (customer) => {
        setSelectedCustomer(customer);
        setSelectedSales("");
        setAssignModalVisible(true);
    };

    // 关闭分配模态框
    const handleCloseAssignModal = () => {
        setAssignModalVisible(false);
        setSelectedCustomer(null);
        setSelectedSales("");
    };

  
    // 注册转正式客户
    const handleRegister = (record) => {
        const updatedData = customerData.map(item =>
            item.key === record.key
                ? { ...item, type: 1, status: 2, registered: true }
                : item
        );
        setFilteredData(updatedData);
        message.success(`【${record.name}】已转为正式客户`);
    };

    // 放入公海
    const handleMoveToPublic = (record) => {
        const updatedData = customerData.map(item =>
            item.key === record.key
                ? { ...item, type: 2, status: 3, followUpPerson: "" }
                : item
        );
        setFilteredData(updatedData);
        message.success(`【${record.name}】已放入公海`);
    };

    // 渲染客户类型标签
    const renderCustomerType = (type, registered) => {
        const config = CUSTOMER_TYPE_MAP[type] || { text: "未知类型", color: "default" };
        return (
            <Tag color={config.color}>
                {config.text}
                {type === 1 && registered && (
                    <Text type="secondary" style={{ marginLeft: 4 }}>(已注册)</Text>
                )}
            </Tag>
        );
    };

    // 渲染跟进状态标签
    const renderFollowStatus = (status) => {
        const config = FOLLOW_STATUS_MAP[status] || { text: "未知状态", color: "default" };
        return <Tag color={config.color}>{config.text}</Tag>;
    };

    // 渲染统计卡片
    const renderStatCard = (title, count, color, icon) => (
        <Card style={{ borderLeft: `4px solid ${color}` }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <div>
                    <Text type="secondary">{title}</Text>
                    <div style={{ fontSize: 24, fontWeight: 600, marginTop: 4 }}>{count}</div>
                </div>
                <div
                    style={{
                        width: 40,
                        height: 40,
                        borderRadius: "50%",
                        backgroundColor: `${color}20`,
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        color
                    }}
                >
                    {icon}
                </div>
            </div>
        </Card>
    );

    // 统计数据
    const stats = {
        total: customerData.length,
        potential: customerData.filter(item => item.type === 0).length,
        official: customerData.filter(item => item.type === 1).length,
        following: customerData.filter(item => item.status === 0 || item.status === 1).length
    };

    // 操作菜单
    // 表格列配置
    const columns = [
        {
            title: "客户编号",
            dataIndex: "customerNo",
            key: "customerNo",
            width: 120,
        },
        {
            title: "客户姓名",
            dataIndex: "name",
            key: "name",
            width: 100,
        },
        {
            title: "联系电话",
            dataIndex: "phone",
            key: "phone",
            width: 130,
        },
        {
            title: "客户类型",
            dataIndex: "type",
            key: "type",
            width: 130,
            render: (type, record) => renderCustomerType(type, record.registered),
        },
        {
            title: "跟进状态",
            dataIndex: "status",
            key: "status",
            width: 110,
            render: (status) => renderFollowStatus(status),
        },
        {
            title: "跟进人",
            dataIndex: "followUpPerson",
            key: "followUpPerson",
            width: 100,
            render: (person) => person || <Text type="secondary">未分配</Text>,
        },
        {
            title: "下次跟进",
            dataIndex: "nextFollowUp",
            key: "nextFollowUp",
            width: 120,
            render: (date) =>
                date === "-" ? (
                    "-"
                ) : (
                    <span style={{ color: new Date(date) < new Date() ? "#f53f3f" : "" }}>
                        {date}
                    </span>
                ),
        },
        {
            title: "客户来源",
            dataIndex: "source",
            key: "source",
            width: 120,
        },
        {
            title: "操作",
            key: "action",
            width: 220,
            render: (_, record) => (
                <Space size="small">
                    <Button type="primary" size="small" onClick={() => handleViewDetail(record.key)}>
                        详情
                    </Button>
                    {/* 仅对非正式客户（type !== 1）显示更多操作 */}
                    {(record.type !== 1 && record.type!==2 )&& (
                        <Dropdown
                            overlay={getActionMenu(record)}
                            trigger={["click"]}
                            placement="bottomRight"
                        >
                            <Button size="small" icon={<MoreOutlined />} />
                        </Dropdown>
                    )}
                </Space>
            ),
        },
    ];

    // 操作菜单
    const getActionMenu = (record) => (
        <Menu>
            {record.type === 0 && !record.followUpPerson && (
                <Menu.Item key="assign" onClick={() => handleOpenAssignModal(record)}>
                    分配跟进人
                </Menu.Item>
            )}
            {record.type === 0 && (
                <Menu.Item key="register" onClick={() => handleRegister(record)}>
                    已注册小程序，转为正式客户
                </Menu.Item>
            )}
            {record.type !== 2 && (
                <Menu.Item key="moveToPublic" onClick={() => handleMoveToPublic(record)}>
                    放入公海
                </Menu.Item>
            )}
           
        </Menu>
    );



    return (
        <div className="customer-management-page">
            {loading ? (
                <Skeleton paragraph={{ rows: 15 }} active />
            ) : (
                <div>
                    {/* 页面标题 */}
                    <div style={{ marginBottom: 20 }}>
                        <Title level={2} className="text-secondary">客户管理</Title>
                        <Paragraph type="secondary">
                            管理客户全生命周期，包括潜在客户、正式客户和公海客户的跟进与维护
                        </Paragraph>
                    </div>

                    {/* 统计卡片 */}
                    <Row gutter={[16, 16]} style={{ marginBottom: 20 }}>
                        <Col xs={24} sm={12} md={6}>
                            {renderStatCard("总客户数", stats.total, "#1890ff", <UserOutlined />)}
                        </Col>
                        <Col xs={24} sm={12} md={6}>
                            {renderStatCard("潜在客户", stats.potential, "#722ed1", <SyncOutlined />)}
                        </Col>
                        <Col xs={24} sm={12} md={6}>
                            {renderStatCard("正式客户", stats.official, "#00b42a", <CheckCircleOutlined />)}
                        </Col>
                        <Col xs={24} sm={12} md={6}>
                            {renderStatCard("跟进中", stats.following, "#ff7d00", <SyncOutlined />)}
                        </Col>
                    </Row>

                    {/* 客户类型标签页 */}
                    <Tabs
                        activeKey={currentTab}
                        onChange={setCurrentTab}
                        style={{ marginBottom: 20 }}
                        items={[
                            { key: "all", label: "全部客户" },
                            { key: "potential", label: <Badge count={stats.potential}>潜在客户</Badge> },
                            { key: "official", label: <Badge count={stats.official}>正式客户</Badge> },
                            { key: "public", label: "公海客户" }
                        ]}
                    />

                    {/* 搜索筛选区域 */}
                    <Card style={{ marginBottom: 20 }}>
                        <Form
                            form={form}
                            layout="inline"
                            initialValues={{ customerType: null, followUpStatus: null }}
                            onFinish={handleSearch}
                        >
                            <Form.Item name="searchKey" label="搜索">
                                <Input
                                    placeholder="姓名/电话/编号"
                                    prefix={<SearchOutlined style={{ color: "#999" }} />}
                                    style={{ width: 200 }}
                                />
                            </Form.Item>

                            <Form.Item name="customerType" label="客户类型">
                                <Select style={{ width: 140 }} placeholder="全部类型">
                                    <Option value={0}>潜在客户</Option>
                                    <Option value={1}>正式客户</Option>
                                    <Option value={2}>公海客户</Option>
                                </Select>
                            </Form.Item>

                            <Form.Item name="followUpStatus" label="跟进状态">
                                <Select style={{ width: 140 }} placeholder="全部状态">
                                    <Option value={0}>待跟进</Option>
                                    <Option value={1}>跟进中</Option>
                                    <Option value={2}>已成交</Option>
                                    <Option value={3}>已放弃</Option>
                                </Select>
                            </Form.Item>

                            <Form.Item>
                                <Space>
                                    <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                                        搜索
                                    </Button>
                                    <Button type="default" onClick={handleReset}>
                                        重置
                                    </Button>
                                    <Button type="primary" icon={<PlusOutlined />} style={{ marginLeft: 8 }}>
                                        新增客户
                                    </Button>
                                </Space>
                            </Form.Item>
                        </Form>
                    </Card>

                    {/* 客户列表 */}
                    <Card>
                        <Table
                            bordered
                            columns={columns}
                            dataSource={filteredData}
                            pagination={{
                                pageSize: 10,
                                showSizeChanger: true,
                                showTotal: (total) => `共 ${total} 条客户记录`
                            }}
                            rowKey="key"
                            scroll={{ x: 1100 }}
                        />
                    </Card>
                </div>
            )}

            {/* 客户详情模态框 */}
            {selectedCustomer && (
                <Modal
                    open={detailModalVisible}
                    title={`客户详情 - ${selectedCustomer.name}`}
                    onCancel={handleCloseDetailModal}
                    footer={[
                        <Button key="cancel" onClick={handleCloseDetailModal}>
                            关闭
                        </Button>,
                    ]}
                    width={900}
                    destroyOnHidden
                    style={{ top: 50 }}
                >
                    <CustomerDetails data={selectedCustomer} />
                </Modal>
            )}

            {/* 分配跟进人模态框 */}

            <Modal
                title={`分配跟进人并添加跟进记录 - ${selectedCustomer?.name}`}
                open={assignModalVisible}
               footer={null}
                destroyOnHidden
                onCancel={()=>setAssignModalVisible(false)}
                style={{top:50}}
            >
              <AllocationEmploye id={selectedCustomer?.key}></AllocationEmploye>
            </Modal>
        </div>
    );
};
